package com.cman777.springc.redis.util;

import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.validation.constraints.NotBlank;
import java.util.Optional;

/**
 * @author chenzhicong
 * @time 2019/11/9 15:36
 * @description
 */
@Component
public class UtilRedis {
    @Autowired
    private RedissonClient redissonClient;
    private static final long MAX_ID = 10000;


    /**
     *  用于生成数据库表数值型id主键
     *  @return 盐(数值) + redis自增变量
     */
    public long nextId(@NotBlank String key, String salt) {
        long newValue = redissonClient.getAtomicLong(key).incrementAndGet();
        return Long.parseLong(Optional.ofNullable(salt).map(String::trim).orElse("") + newValue);
    }


    /**
     *  用于生成数据库表的字符串型id主键
     *   @return 时间戳 + 盐 + redis自增变量（到10000重新计数）
     *
     */
    public String nextStringId(@NotBlank String key,String salt) {

        RAtomicLong rAtomicLong = redissonClient.getAtomicLong(key.trim());
        //到10000则重新计数
        rAtomicLong.compareAndSet(MAX_ID,0);
        return System.currentTimeMillis() + Optional.ofNullable(salt).map(String :: trim).orElse("") + rAtomicLong.incrementAndGet();
    }
}
